<template>
  <div class="dashboard-container">
    <!-- 销售总金额模块 -->
    <div class="summary-stats">
      <div class="box weekly-summary">
        <div class="header">
          <div class="title">本周售卖总金额</div>
        </div>
        <div class="body">
          <div class="amount-display">
            ¥{{ formatAmount(weeklyTotalAmount) }}
          </div>
          <div class="period-info">
            统计周期: {{ currentWeekRange }}
          </div>
        </div>
      </div>
      <div class="box monthly-summary">
        <div class="header">
          <div class="title">本月售卖总金额</div>
        </div>
        <div class="body">
          <div class="amount-display">
            ¥{{ formatAmount(monthlyTotalAmount) }}
          </div>
          <div class="period-info">
            统计周期: {{ selectedMonth }}
          </div>
        </div>
      </div>
    </div>

    <!-- 本周售卖情况 -->
    <div class="box current-week-sales">
      <div class="header">
        <div class="title">
          本周售卖情况
          <span class="sub-title">{{ currentWeekRange }}</span>
        </div>
        <div class="actions">
          <el-select v-model="salesTimePeriod" size="mini" @change="handleSalesTimePeriodChange">
            <el-option label="本周" value="current" />
            <el-option label="上周" value="last" />
          </el-select>
        </div>
      </div>
      <div class="body">
        <v-chart v-if="currentWeekData.length > 0" :option="currentWeekOption" style="height: 300px" />
        <el-empty v-else description="暂无本周销售数据" />
      </div>
    </div>

    <!-- 本月售卖情况 -->
    <div class="box monthly-sales">
      <div class="header">
        <div class="title">
          本月售卖情况
          <span class="sub-title">{{ selectedMonth }}</span>
        </div>
      </div>
      <div class="body">
        <v-chart v-if="monthlyData.length > 0" :option="monthlyOption" style="height: 350px" />
        <el-empty v-else description="暂无月度销售数据" />
      </div>
    </div>

    <!-- 部门好吃榜 -->
    <div class="box department-ranking">
      <div class="header">
        <div class="title">
          部门好吃榜
          <span class="sub-title">{{ rankingDateRange }}</span>
        </div>
        <div class="actions">
          <el-select v-model="rankingTimePeriod" size="mini" @change="handleRankingTimePeriodChange">
            <el-option label="本周" value="current" />
            <el-option label="上周" value="last" />
          </el-select>
        </div>
      </div>
      <div class="body">
        <div v-if="departmentRanking.length > 0" class="ranking-list">
          <div class="ranking-header">
            <div class="rank">排名</div>
            <div class="department">部门</div>
            <div class="amount">订购金额</div>
          </div>
          <div
            v-for="(item, index) in departmentRanking"
            :key="item.deptId"
            class="ranking-item"
          >
            <div class="rank" :class="{'top3': index < 3}">
              <span class="rank-icon">
                <el-icon v-if="index === 0" class="top-icon"><medal /></el-icon>
              </span>
              <span class="rank-number">{{ index + 1 }}</span>
            </div>
            <div class="department">
              {{ item.deptName }}
            </div>
            <div class="amount">
              ¥{{ formatAmount(item.totalAmount) }}
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无部门排行数据" />
      </div>
    </div>
  </div>
</template>

<script>
import { getWeeklySales, getMonthlySales, getDepartmentRanking } from '@/api/home.js'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  DataZoomComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { Medal } from '@element-plus/icons-vue'

use([
  CanvasRenderer,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  DataZoomComponent
])

export default {
  components: { VChart, Medal },
  data() {
    return {
      salesTimePeriod: 'current',
      rankingTimePeriod: 'current',

      currentWeekData: [],
      currentWeekRange: '',
      weeklyTotalAmount: 0,

      selectedMonth: '',
      monthlyType: '1',
      monthlyData: [],
      monthlyTotalAmount: 0,

      departmentRanking: [],
      rankingDateRange: ''
    }
  },
  computed: {
    currentWeekOption() {
      return {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>¥{c}'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.currentWeekData.map(item => item.productName),
          axisLabel: {
            interval: 0,
            rotate: 30,
            textStyle: {
              fontSize: 12
            }
          },
          axisLine: {
            show: true
          }
        },
        yAxis: {
          type: 'value',
          name: '金额 (元)',
          axisLabel: {
            formatter: '{value}元'
          }
        },
        dataZoom: [{
          type: 'inside',
          start: 0,
          end: 100
        }],
        series: [{
          name: '销售金额',
          type: 'bar',
          data: this.currentWeekData.map(item => item.totalAmount),
          itemStyle: {
            color: (params) => {
              const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de']
              return colors[params.dataIndex % colors.length]
            }
          },
          label: {
            show: true,
            position: 'top',
            formatter: '¥{c}'
          },
          barWidth: '30%'
        }]
      }
    },
    monthlyOption() {
      const allWeeks = [1, 2, 3, 4];
      const weeklyMap = {};

      this.monthlyData.forEach(item => {
        weeklyMap[item.weekNumber] = item.totalAmount;
      });

      const completeData = allWeeks.map(weekNum => ({
        weekNumber: weekNum,
        totalAmount: weeklyMap[weekNum] || 0
      }));

      return {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const param = params[0];
            const weekNum = param.name;
            const amount = param.value;
            if (amount === 0) {
              return `${weekNum}<br/>无销售数据`;
            }
            return `${weekNum}<br/>¥${amount}`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: completeData.map(item => `第${item.weekNumber}周`),
          name: '周次',
          axisLabel: {
            rotate: 0,
            textStyle: {
              fontSize: 12
            }
          },
          axisLine: {
            show: true
          }
        },
        yAxis: {
          type: 'value',
          name: '金额 (元)',
          axisLabel: {
            formatter: '{value}元'
          }
        },
        series: [{
          name: '销售金额',
          type: 'bar',
          data: completeData.map(item => item.totalAmount),
          itemStyle: {
            color: (params) => {
              if (completeData[params.dataIndex].totalAmount === 0) {
                return '#c0c4cc';
              }
              return '#91cc75';
            }
          },
          label: {
            show: true,
            position: 'top',
            formatter: (params) => {
              if (params.value === 0) {
                return '';
              }
              return `¥${params.value}`;
            }
          },
          barWidth: '40%'
        }]
      }
    }
  },
  mounted() {
    this.setDefaultTime()
    this.loadCurrentWeekData()
    this.loadMonthlyData()
    this.loadDepartmentRanking()
  },
  methods: {
    setDefaultTime() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      this.selectedMonth = `${year}-${month}`
      this.updateWeekRange()
    },

    updateWeekRange() {
      const salesDate = this.getTimeForPeriod(this.salesTimePeriod)
      this.currentWeekRange = this.getWeekRangeDisplay(salesDate)
      const rankingDate = this.getTimeForPeriod(this.rankingTimePeriod)
      this.rankingDateRange = this.getWeekRangeDisplay(rankingDate)
    },

    getWeekRangeDisplay(date) {
      const monday = new Date(date)
      monday.setDate(monday.getDate() - monday.getDay() + (monday.getDay() === 0 ? -6 : 1))
      const sunday = new Date(monday)
      sunday.setDate(sunday.getDate() + 6)
      const formatDate = (d) => `${d.getFullYear()}.${d.getMonth() + 1}.${d.getDate()}`
      return `${formatDate(monday)} ~ ${formatDate(sunday)}`
    },

    getTimeForPeriod(timePeriod) {
      const now = new Date()
      if (timePeriod === 'last') {
        return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
      }
      return now
    },

    getFormattedDateForPeriod(timePeriod) {
      const date = this.getTimeForPeriod(timePeriod)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    handleSalesTimePeriodChange() {
      this.updateWeekRange()
      this.loadCurrentWeekData()
    },

    handleRankingTimePeriodChange() {
      this.updateWeekRange()
      this.loadDepartmentRanking()
    },

    async loadCurrentWeekData() {
      try {
        const time = this.getFormattedDateForPeriod(this.salesTimePeriod)
        const res = await getWeeklySales({
          time: time,
          typeId: '1'
        })
        if (res.data && res.data.data) {
          this.currentWeekData = res.data.data
            .map(item => ({
              productName: item.productName,
              totalAmount: item.totalAmount
            }))
            .sort((a, b) => b.totalAmount - a.totalAmount)
          this.weeklyTotalAmount = res.data.salesAmount || 0
        } else {
          this.currentWeekData = []
          this.weeklyTotalAmount = 0
        }
      } catch (error) {
        console.error('加载当周数据失败:', error)
        this.currentWeekData = []
        this.weeklyTotalAmount = 0
      }
    },

    async loadMonthlyData() {
      try {
        const res = await getMonthlySales({
          time: this.selectedMonth,
          typeId: this.monthlyType
        })
        if (res.data && res.data.data) {
          this.monthlyData = res.data.data
            .map(item => ({
              weekNumber: item.weekNumber,
              totalAmount: item.totalAmount
            }))
            .sort((a, b) => a.weekNumber - b.weekNumber)
          this.monthlyTotalAmount = res.data.salesAmount || 0
        } else {
          this.monthlyData = []
          this.monthlyTotalAmount = 0
        }
      } catch (error) {
        console.error('加载月度数据失败:', error)
        this.monthlyData = []
        this.monthlyTotalAmount = 0
      }
    },

    async loadDepartmentRanking() {
      try {
        const time = this.getFormattedDateForPeriod(this.rankingTimePeriod)
        const res = await getDepartmentRanking({
          time: time,
          typeId: '1'
        })
        this.departmentRanking = res.data || []
      } catch (error) {
        console.error('加载部门排行失败:', error)
        this.departmentRanking = []
      }
    },

    formatAmount(value) {
      if (!value) return '0.00'
      if (value > 10000) {
        return (value / 10000).toFixed(2) + '万'
      }
      return value.toFixed(2)
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto auto auto auto;
  grid-gap: 20px;
  padding: 20px;
  background-color: #ffffff;
  background-size: cover;
  background-position: center center;
  background-repeat: no-repeat;
  min-height: 100vh;
  position: relative;
}

.summary-stats {
  grid-column: 1 / 3;
  grid-row: 1 / 2;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.weekly-summary, .monthly-summary {
  display: flex;
  flex-direction: column;
}

.amount-display {
  font-size: 28px;
  font-weight: bold;
  color: #e6a23c;
  padding: 20px 0;
  text-align: center;
}

.period-info {
  color: #606266;
  text-align: center;
  font-size: 14px;
}

.current-week-sales {
  grid-column: 1 / 2;
  grid-row: 2 / 3;
}

.monthly-sales {
  grid-column: 1 / 2;
  grid-row: 3 / 4;
}

.department-ranking {
  grid-column: 2 / 3;
  grid-row: 2 / 4;
}

.box {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
  z-index: 1;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  background: #f5f7fa;
}

.title {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.sub-title {
  font-size: 13px;
  color: #909399;
  margin-left: 10px;
  font-weight: normal;
}

.actions {
  display: flex;
  gap: 10px;
}

.body {
  padding: 15px;
}

.ranking-list {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.ranking-header, .ranking-item {
  display: grid;
  grid-template-columns: 70px 1fr 120px; /* 增加排名列宽度 */
  align-items: center;
  padding: 12px 15px;
}


.ranking-header {
  background: #f5f7fa;
  font-weight: bold;
  color: #606266;
}

.ranking-item {
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.3s;
}

.ranking-item:hover {
  background-color: #f5f7fa;
}

.ranking-item:last-child {
  border-bottom: none;
}

.rank {
  text-align: center;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 24px; /* 固定最小高度确保对齐 */
  font-size: 14px;
  line-height: 1.2;
}


.top3 {
  color: #e6a23c;
  font-size: 16px;
}

.rank-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
}

.top-icon {
  color: #e6a23c;
  font-size: 14px;
  margin-right: 1px;
}

.rank-number {
  font-size: 14px;
  line-height: 1; /* 重置行高避免基线偏移 */
  text-align: center;
  vertical-align: middle;
}

.department {
  font-weight: 500;
}

.amount {
  text-align: right;
  font-weight: bold;
  color: #e6a23c;
}
</style>
